require "Object"

lingdangCount = 0

--LingDang class
LingDang = Object:new{
	lingdangID = nil,
	factory = nil,
	bDispeared = false,
	minHeight = 120,
	collideMusic = nil,
	world = nil,
}

function LingDang:onEnter()
	Misc:log("LingDang : onEnter .. " .. Misc:getNodeName(self))
	self.collideMusic = "collide.mp3"
end

function LingDang:dispear()
	local fadeOut = CCFadeTo:create(0.5, 0)
	local deleteAct = VDeleteNode:action()
	local seqArray = CCArray:create(2)
	seqArray:addObject(fadeOut)
	seqArray:addObject(deleteAct)
	
	self:runAction(CCSequence:create(seqArray))
	self.bDispeared = true
end

function LingDang:showScore(score)
	score = score*self.world.shuangbei
	self.world.scoreLabel:setString(tostring(score))
	self.world.scoreLabel:setOpacity(255)
	local pos = self:getParent():convertToWorldSpace(self:getPositionLua())
	pos = self.world:convertToNodeSpace(pos)
	self.world.scoreLabel:setPosition(pos.x, pos.y)
	self.world.scoreLabel:runAction(CCFadeTo:create(1, 0))
	self.world.score = self.world.score + score
	g_scoreLabel:setString(tostring(self.world.score))
end

function LingDang:collide()
	SimpleAudioEngine:sharedEngine():playEffect(self.collideMusic);
	local cc2dNode = CC2DFileCache:sharedCC2DFileCache():addCC2DNode("baozha.cc2d")
	local ccNode = cc2dNode:createCCNode(self)
	local pos = self:getParent():convertToWorldSpace(self:getPositionLua())
	ccNode:setScale(1/self:getScale())
	local size = self:getContentSize()
	local anchorPoint = self:getAnchorPoint()
	ccNode:setPosition(size.width*0.5, size.height*0.5)
	
	local moveBy = CCMoveBy:create(0.5, CCPoint(0, -20))
	self:runAction(CCEaseSineOut:create(moveBy))
	self:dispear()
end

function LingDang:tick(dt)
	local worldPos = self:getParent():convertToWorldSpace(self:getPositionLua())
	local nodePos = self.factory:getParent():convertToNodeSpace(worldPos)
	
	if (worldPos.y < -g_winSize.height*1.0) or (nodePos.y < self.minHeight) then
		self:dispear()
	end
end

function LingDang:onExit()
	self.factory.lingdangs[self.lingdangID] = nil
end


function LingDang:create(lingdangFile, factory, lingdang)
	local newLingDang = lingdang or LingDang:new()
	newLingDang.factory = factory
	self.world = factory.world
	
	local cc2dNode = CC2DFileCache:sharedCC2DFileCache():addCC2DNode(lingdangFile)
	local ccLingDang = tolua.cast(cc2dNode:createCCNode(factory), "CCSprite")
	
	lingdangCount = lingdangCount + 1
	newLingDang.lingdangID = lingdangCount
	Misc:setNodeName(ccLingDang, "lingdang" .. lingdangCount)
	
	tolua.setpeer(ccLingDang, newLingDang)
	
	local function onEnterOrExit(eventType)
		if eventType == kCCNodeOnExit then
			ccLingDang:onExit()
		else
			ccLingDang:onEnter()
		end
	end
	
	ccLingDang:registerScriptHandler(onEnterOrExit)
	
	if ccLingDang:isRunning() then
		ccLingDang:onEnter()
	end
	return ccLingDang
end